package com.oliver.proxy.midjourney.interfaces.controller;

import com.oliver.proxy.midjourney.interfaces.dto.DownloadDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.nio.file.Files;
import java.nio.file.Path;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

@RestController
@RequestMapping("/submit")
@RequiredArgsConstructor
public class DownloadPicController {

    @PostMapping("/download-and-zip")
    @ResponseBody
    public ResponseEntity<Resource> downloadAndZipImages(@RequestBody List<DownloadDTO> dto) throws IOException {
        // 创建临时目录来保存图片和ZIP文件
        Path tempDir = Files.createTempDirectory("downloaded_images");
        Path zipFilePath = tempDir.resolve("images.zip");

        try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zipFilePath))) {
            for (DownloadDTO downloadDTO : dto) {
                String url = downloadDTO.getUrl();
                String prompt = downloadDTO.getPrompt();
                prompt = prompt.replaceAll(" ", "_");
                prompt = prompt.replaceAll(".", "");
                BufferedImage image = ImageIO.read(new URL(url));
                int width = image.getWidth();
                int height = image.getHeight();
                int quarterWidth = width / 2;
                int quarterHeight = height / 2;

                for (int row = 0; row < 2; row++) {
                    for (int col = 0; col < 2; col++) {
                        BufferedImage croppedImage = new BufferedImage(quarterWidth, quarterHeight, BufferedImage.TYPE_INT_RGB);
                        Graphics2D g2d = croppedImage.createGraphics();
                        g2d.drawImage(image, 0, 0, quarterWidth, quarterHeight, col * quarterWidth, row * quarterHeight, (col + 1) * quarterWidth, (row + 1) * quarterHeight, null);
                        g2d.dispose();

                        long timestamp = System.currentTimeMillis();
                        String fileName = "/Users/oliver/pic/image_" + "_part_" + (row * 2 + col + 1) + timestamp + ".jpg";
//                      String fileName = "/Users/oliver/pic/image_" + prompt + "_" + timestamp + ".jpg";
                        Path filePath = tempDir.resolve(fileName);

                        System.out.println("Saving image to: " + filePath.toAbsolutePath());

                        ImageIO.write(croppedImage, "jpg", filePath.toFile());

                        ZipEntry entry = new ZipEntry(fileName);
                        zos.putNextEntry(entry);
                        Files.copy(filePath, zos);
                        zos.closeEntry();
                    }
                }
            }

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "images.zip");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(new UrlResource(zipFilePath.toUri()));
        }


    }
}

